package metadata_tab

import (
	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/model"
	"file_explorer/service/eventbus"
	"file_explorer/service/third_program"
	"file_explorer/view/packed_widgets"
	"file_explorer/view/store"

	"fyne.io/fyne/v2"
)

type MetadataPreview struct {
	*packed_widgets.Table

	tabCtx *store.MetadataTabContext
}

// 撤销EditForm的改动，重置为初始状态
func (preview *MetadataPreview) resetCheckItems() {
	checkIndexList := preview.Checklist.GetCheckIndexList()
	for _, checkIndex := range checkIndexList {
		preview.tabCtx.FileInfos[checkIndex].New = preview.tabCtx.FileInfos[checkIndex].Old.Clone()
	}
	preview.Table.Refresh()
}

// 从context回写CheckList状态
func (preview *MetadataPreview) reloadCheckList() {
	checkItemSet := make(map[*model.ModifiedFileInfo]struct{})
	for _, checkItem := range preview.tabCtx.CheckFiles {
		checkItemSet[checkItem] = struct{}{}
	}
	checkIndexList := make([]int, 0, len(checkItemSet))
	for i, fileInfo := range preview.tabCtx.FileInfos {
		if _, ok := checkItemSet[fileInfo]; ok {
			checkIndexList = append(checkIndexList, i)
		}
	}
	preview.Checklist.SetCheckIndexList(checkIndexList)
}

func NewMetadataPreview(tabCtx *store.MetadataTabContext) *MetadataPreview {
	preview := &MetadataPreview{
		tabCtx: tabCtx,
		Table:  packed_widgets.NewTable(),
	}

	preview.Table.SetGetData(func(index int) interface{} {
		return tabCtx.FileInfos[index].New
	})

	preview.Table.SetGetDataLength(func() int {
		return len(tabCtx.FileInfos)
	})

	preview.Table.AddColumn(
		packed_widgets.NewTableColumn().
			SetHeader("名称").
			SetWidth(200).
			SetIconGetter(func(data interface{}) fyne.Resource {
				return data.(*model.FileInfo).GetIcon()
			}).
			SetTextGetter(func(data interface{}) string { return data.(*model.FileInfo).Name }).
			SetOrderBy(func(asc bool) {
				preview.tabCtx.SortFileInfos(
					util.GetComparatorByPriority[*model.ModifiedFileInfo](
						asc,
						func(a, b *model.ModifiedFileInfo) int {
							return int(b.New.Type - a.New.Type)
						},
						func(a, b *model.ModifiedFileInfo) int {
							return util.CmpText(a.New.Name, b.New.Name)
						},
					),
				)
			}).
			SetDefaultOrder(),
	)

	preview.Table.AddColumn(
		packed_widgets.NewTableColumn().
			SetHeader("评分").
			SetWidth(60).
			SetTextGetter(func(data interface{}) string { return data.(*model.FileInfo).GetScoreStr() }).
			SetOrderBy(func(asc bool) {
				preview.tabCtx.SortFileInfos(
					util.GetComparatorByPriority[*model.ModifiedFileInfo](
						asc,
						func(a, b *model.ModifiedFileInfo) int {
							return int(b.New.Type - a.New.Type)
						},
						func(a, b *model.ModifiedFileInfo) int {
							return b.New.GetScore() - a.New.GetScore()
						},
						func(a, b *model.ModifiedFileInfo) int {
							return util.CmpText(a.New.Name, b.New.Name)
						},
					),
				)

			}),
	)

	preview.Table.AddColumn(
		packed_widgets.NewTableColumn().
			SetHeader("标签").
			SetWidth(100).
			SetTextGetter(func(data interface{}) string { return data.(*model.FileInfo).GetTagsStr() }),
	)

	preview.Table.AddColumn(
		packed_widgets.NewTableColumn().
			SetHeader("备注").
			SetWidth(300).
			SetTextGetter(func(data interface{}) string { return data.(*model.FileInfo).GetNote() }),
	)

	preview.Table.AddColumn(
		packed_widgets.NewTableColumn().
			SetHeader("链接").
			SetWidth(150).
			SetTextGetter(func(data interface{}) string { return data.(*model.FileInfo).GetUrl() }),
	)

	preview.Table.Build()

	// 双击文件
	preview.Table.OnDoubleTapped = func(row int, col int) {
		fileInfo := preview.tabCtx.FileInfos[row].New
		if fileInfo.IsDir() {
			// 进入目录
			log.Info("打开目录：%s", fileInfo.GetPath())
			fileTabContext := store.NewFileTabContext(preview.tabCtx.GetGlobalContext(), fileInfo.GetPath())
			preview.tabCtx.GetGlobalContext().AddTab(fileTabContext)
		} else {
			// 打开文件
			log.Info("打开文件：%s", fileInfo.GetPath())
			third_program.GetCaller().OpenFile(fileInfo.GetPath())
		}
	}

	// 排序时同步checklist
	preview.Table.RegisterConsumer(eventbus.EventKeyWidgetTableOrderChange, func(event *model.Event) {
		log.Info("元数据页文件列表排序变更，路径：%s", preview.tabCtx.Path)
		preview.reloadCheckList()
	})

	// vList内check list更新时同步到tab context
	preview.Checklist.RegisterConsumer(eventbus.EventKeyWidgetChecklistChange, func(event *model.Event) {
		checkIndexList := preview.Checklist.GetCheckIndexList()
		checkList := make([]*model.ModifiedFileInfo, len(checkIndexList))
		for i, checkIndex := range checkIndexList {
			checkList[i] = preview.tabCtx.FileInfos[checkIndex]
		}
		preview.tabCtx.CheckFiles = checkList
	})

	return preview
}
